﻿using MySql.Data.MySqlClient;
using Nethereum.Hex.HexConvertors.Extensions;
using Nethereum.Signer;
using Nethereum.Web3.Accounts;
using System;
using System.Text;

namespace CreateNewEthAccountToSql
{
    class CreateNewWallet
    {
        const String connetStr = "server=192.168.1.129;port=3306;user=root;password=123456; database=wallet_db;";
        public static void Create()
        {
            MySqlConnection conn = new MySqlConnection(connetStr);
            try
            {
                conn.Open();//打开通道，建立连接，可能出现异常,使用try catch语句
                Console.WriteLine("已经建立连接");
                //在这里使用代码对数据库进行增删查改

                StringBuilder strlist = new StringBuilder();
                strlist.Append("insert into wallet_address (wallet_address, private_key)");
                string model = "select '{0}','{1}' union all \n";
                int count = 2000;
                for (int i = 0; i < count; i++)
                {
                    var ecKey = EthECKey.GenerateKey();
                    var privateKey = ecKey.GetPrivateKeyAsBytes().ToHex();
                    var account = new Account(privateKey);
                    var publickey = account.Address;

                    if (i == (count - 1))
                    {
                        strlist.Append(string.Format("select '{0}','{1}'", publickey, privateKey));
                    }
                    else
                    {
                        strlist.Append(string.Format(model, publickey, privateKey));
                    }
                }

                string sqlCmd = strlist.ToString();

                Console.WriteLine("开始写入数据到MySql");
                MySqlCommand cmd = new MySqlCommand(sqlCmd, conn);
                int result = cmd.ExecuteNonQuery();

                Console.WriteLine("执行成功!!");
            }
            catch (MySqlException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                conn.Close();
            }
        }
    }
}
